#!/bin/bash

set -x
nvim_name='nvim-linux-x86_64'
nvim_version=${nvim_version:-"v0.11.4"}
nvim_env_var="${nvim_env_var:-NVIM_HOME}"
nvim_download_path="/tmp/nvim-download"

rc_path="${rc_path:-${HOME}/.bashrc}"
softwares_path="${softwares_path:-/opt/softwares}"
nvim_home="${softwares_path}/${nvim_name}"
proxy_prefix=${proxy_prefix:-"https://ghproxy.net/"}
set +x

add_env_str=$(
  cat <<EOF

# ${nvim_env_var} 
${nvim_env_var}="${nvim_home}"
export PATH="\${PATH}:\${${nvim_env_var}}/bin"
EOF
)

download_nvim() {

  mkdir -p "${nvim_download_path}"
  echo "start download nvim..."
  echo "curl -C - -o ${nvim_download_path}/${nvim_name}.tar.gz -LO ${proxy_prefix}https://github.com/neovim/neovim/releases/download/${nvim_version}/${nvim_name}.tar.gz"
  curl -C - -o "${nvim_download_path}/${nvim_name}.tar.gz" -LO "${proxy_prefix}https://github.com/neovim/neovim/releases/download/${nvim_version}/${nvim_name}.tar.gz"
  sudo mkdir -p "${softwares_path}"
  sudo rm -rf "${nvim_home}"
  sudo tar -C "${softwares_path}" -xzf "${nvim_download_path}/${nvim_name}.tar.gz"
}

main() {

  download_nvim

  if cat "${rc_path}" | grep -q "${nvim_env_var}"; then
    echo "find ${nvim_env_var} in ${rc_path}:"
    echo ''
    cat "${rc_path}" | grep "${nvim_env_var}"
    echo ''
    echo "please add nvim env var into ${rc_path} manally:"
    echo ""
    echo "${add_env_str}"
  else
    echo "${add_env_str}" >>"${rc_path}"
  fi
}

main
